import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

public class Client {
    public static void main(String[] args) {
        // 初始化论文列表（增加论文数量确保有足够选择）
        PaperList list = new PaperList("Rainy", Arrays.asList(
                new Thesis("Computer Science"),
                new ConferencePaper("AI Conference"),
                new JournalPaper("Nature Technology"),
                new Thesis("Physics Research"),
                new ConferencePaper("Network Security"),
                new JournalPaper("Advanced Materials"),  // 新增
                new ConferencePaper("Data Mining")      // 新增
        ));

        // 创建学生（调整选择数量使其更合理）
        List<Student> students = Arrays.asList(
                new Student("Cloudy", 1, PaperType.Thesis),
                new Student("Sunny", 2, PaperType.JournalPaper),
                new Student("Windy", 1, PaperType.Any),
                new Student("Rainy", 2, PaperType.ConferencePaper)  // 从3改为2
        );

        ExecutorService executor = Executors.newFixedThreadPool(students.size());
        CountDownLatch latch = new CountDownLatch(students.size());

        for (Student s : students) {
            executor.execute(() -> {
                try {
                    List<Paper> selected = list.selectPaperByRandom(s);
                    System.out.printf("%s selected: %s%n",
                            s.getName(),
                            selected.stream()
                                    .map(Paper::getTitle)
                                    .collect(Collectors.joining(", ")));
                } catch (NoEnoughPapersException e) {
                    System.err.println(e.getMessage());
                } catch (IllegalArgumentException e) {
                    System.err.println("Error: " + e.getMessage());
                } finally {
                    latch.countDown();
                }
            });
        }

        try {
            if (!latch.await(2, TimeUnit.SECONDS)) {
                System.err.println("Warning: Timeout waiting for selections");
            }

            System.out.println("\nFinal Selection Results:");
            System.out.println(list.getSelectionResult());

            StudentCountVisitor visitor = new StudentCountVisitor();
            list.getSelectionResult().accept(visitor);
            System.out.println("Unique students selected: " + visitor.getCount());

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            executor.shutdown();
        }
    }
}